package com.yami.shop.mystery.common.listener;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.bean.event.InviteEvent;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.UserInvite;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.UserInviteService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.Date;


@Slf4j
@Component("inviteListener")
@AllArgsConstructor
public class InviteListener {

    @Autowired
    private ActivityPresellService activityPresellService;
    @Autowired
    private UserInviteService userInviteService;

    @EventListener(InviteEvent.class)
    public void inviteListener(InviteEvent event) {
        // 实名 修改 实名状态
        if(event.getIsReal()){
            UserInvite userInvite = userInviteService.getOne(new QueryWrapper<UserInvite>().eq("user_id", event.getUserId()));
            if(ObjectUtil.isNotEmpty(userInvite)){
                userInvite.setIsReal("1");
                userInvite.setRealTime(new Timestamp(new Date().getTime()));
                userInviteService.updateById(userInvite);
            }
        }else {
            // 是否 有 正在进行的 拉新活动
            QueryWrapper<ActivityPresell> activityPresellQueryWrapper = new QueryWrapper<>();
            activityPresellQueryWrapper.le("activity_start_time",new Date());
            activityPresellQueryWrapper.ge("activity_end_time",new Date());
            activityPresellQueryWrapper.eq("del_flag",0);
            activityPresellQueryWrapper.eq("activity_type",6);
            ActivityPresell one = activityPresellService.getOne(activityPresellQueryWrapper);
            if(ObjectUtil.isEmpty(one)){
                return;
            }
            // 查询是否添加
            UserInvite userInviteData = userInviteService.getOne(new QueryWrapper<UserInvite>()
                    .eq("user_id", event.getUserId())
                    .eq("invite_user_id", event.getInviteUserId())
                    .eq("activity_id", one.getId()));
            if(ObjectUtil.isNotEmpty(userInviteData)){
                return;
            }
            // 新增 邀请绑定关系
            UserInvite userInvite = new UserInvite();
            userInvite.setIsReal("0");
            userInvite.setUserId(event.getUserId());
            userInvite.setInviteUserId(event.getInviteUserId());
            userInvite.setActivityId(one.getId());
            userInviteService.save(userInvite);
        }

    }

}
